import React, {Component} from 'react';
import {
    Button,
    Input,
    Card,
    Table,
    Field,
    Tag,
    Message,
} from '@alifd/next';
import './sku.scss';

const {
    Closeable: CloseableTag
} = Tag;

class Sku extends Component {

    constructor(propes) {
        super(propes);
        this.state = {
            specList: [
                {
                    name: '颜色',
                    value: ['黑色', '黄色', '白色']
                },
                // {
                //     name: '尺寸',
                //     value: ['xl', 'xxl', 'xxxl']
                // },
            ],
            specAttrList:[
                {
                    attr_list:{'颜色':'黑色'},
                    price:0,
                    bar_code:''
                },
                {
                    attr_list:{'颜色':'黄色'},
                    price:5,
                    bar_code:''
                },
                {
                    attr_list:{'颜色':'白色'},
                    price:6,
                    bar_code:''
                },
            ]
        };
        this.field = new Field(this, {
            onChange: (name, value) => {
                let inputName = name.split('_');
                let tagName = '';
                name = inputName.length > 0 ? inputName[0] : name;
                switch (name) {
                    case 'tagTitle':
                        let specList = this.state.specList;
                        specList[inputName[1]].name = value;
                        this.handleSpecChange(specList);
                        break;
                    case 'barcode':
                        name = 'bar_code';
                    case 'price':
                        let specAttrList = this.state.specAttrList;
                        specAttrList[inputName[1]][name] = value;
                        this.setState({specAttrList:specAttrList})
                        break;
                    default:
                        break;
                }
            }
        });

        this.addSpec = this.addSpec.bind(this);
        this.getSpecAttr = this.getSpecAttr.bind(this);
        this.countSum = this.countSum.bind(this);
        this.showTd = this.showTd.bind(this);
    }

    render() {
        const init = this.field.init;
        const {specList,specAttrList} = this.state;
        const renderAttr = [];
        const renderSpec = [];

        for (let i = 0; i < this.countSum(0); i++) {
            renderAttr.push(<tr key={i}>
                {specList.length > 0 && specList.map((item, index) => {
                    let tagName = this.getSpecAttr(index, i);
                    return (
                        <td key={index}>{tagName}</td>
                    )
                })}
            </tr>);
            renderSpec.push(<tr key={i}>
                {specList.length > 0 && specList.map((item, index) => {
                    if (this.showTd(index, i)) {
                        let tagName = this.getSpecAttr(index, i);
                        let n = index + 1;
                        return (
                            <td rowSpan={this.countSum(n)} key={index}>{tagName}</td>
                        )
                    }
                })}
                <td>
                    <Input {...init(`barcode_${i}`, {})} value={specAttrList[i].bar_code} placeholder="请输入商品条形码"/>
                </td>
                <td>
                    <Input {...init(`price_${i}`, {})} value={specAttrList[i].price} placeholder="请输入销售价"/>
                </td>
            </tr>);
        }

        return (
            <div className="specifications" style={{padding: 20}}>
                <Card {...{
                    style: {width: '100%', marginTop: '20px'},
                    title: '商品规格设置',
                    subTitle: '(请点击右边按钮新增规格)',
                    extra: <Button onClick={this.addSpec} type="primary">添加规格</Button>,
                }} contentHeight="auto">
                    <div className="card-placeholder">
                        {specList.length > 0 && specList.map((item, index) => {
                            return (
                                <div className="taglist" key={index}>
                                    <div className="tagtitle">
                                        <Button style={{float: 'right'}} type="primary" warning
                                                onClick={this.delSpec.bind(this, index)}>删</Button>
                                        <Input {...init(`tagTitle_${index}`, {})} value={item.name}
                                               placeholder="输入商品规格"/>
                                    </div>
                                    <div className="tagcustom">
                                        <div className="custom">
                                            {item.value.length > 0 && item.value.map((v, i) => {
                                                return <CloseableTag onClose={this.delAttr.bind(this, index, i)} key={i}
                                                                     type="normal">{v}</CloseableTag>;
                                            })}
                                            <div style={{display: 'inline-block', margin: '5px'}}>
                                                <Input {...init(`tagName[${index}]`, {initValue: ''})}
                                                       placeholder="多个属性请以空格隔开"/>
                                                <Button type="primary"
                                                        onClick={this.addSpecAttr.bind(this, index)}>新增</Button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </Card>
                <Card {...{
                    style: {width: '100%', marginTop: '20px'},
                    title: '规格参数',
                    //subTitle: '(提供批量处理)',
                }} contentHeight="auto">
                    <div className="custom-content">
                        <div className="next-table">
                            <table>
                                <thead>
                                <tr>
                                    {specList.length > 0 && specList.map((item, index) => {
                                        return (
                                            <th key={index}>{item.name}</th>
                                        );
                                    })}
                                    <th>规格编码</th>
                                    <th>销售价（元）</th>
                                </tr>
                                </thead>
                                <tbody>
                                {renderSpec}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </Card>

                <Card {...{
                    style: {width: '100%', marginTop: '20px'},
                    title: '规格属性',
                }} contentHeight="auto">
                    <div className="custom-content">
                        <div className="next-table">
                            <table>
                                <thead>
                                <tr>
                                    {specList.length > 0 && specList.map((item, index) => {
                                        return (
                                            <th key={index}>{item.name}</th>
                                        );
                                    })}
                                </tr>
                                </thead>
                                <tbody>
                                    {renderAttr}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </Card>
            </div>
        );
    }

    /**
     * 根据传入的条件，来判断是否显示该td
     * [如果当前项目下没有属性，则不显示]
     * @param specIndex
     * @param index
     * @returns {boolean}
     */
    showTd(specIndex, index) {
        if (!this.state.specList[specIndex]) {
            return false;
        } else if (index % this.countSum(specIndex + 1) === 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据传入的属性值，拿到相应规格的属性
     * @param specIndex
     * @param index 所有属性在遍历时的序号
     * @returns {string}
     */
    getSpecAttr(specIndex, index) {
        // 获取当前规格项目下的属性值
        let specList = this.state.specList;
        const currentValues = specList[specIndex].value;
        // 判断是否是最后一个规格项目
        let indexCopy = (specList[specIndex + 1] && specList[specIndex + 1].value.length)
            ? index / this.countSum(specIndex + 1)
            : index;
        const i = Math.floor(indexCopy % currentValues.length);
        return (i.toString() !== 'NaN') ? currentValues[i] : '';
    }

    /**
     * 计算属性的乘积
     * @param specIndex
     * @returns {number}
     */
    countSum(specIndex) {
        let num = 1;
        this.state.specList.forEach((item, index) => {
            if (index >= specIndex && item.value.length) {
                num *= item.value.length;
            }
        });
        return num;
    }

    /**
     * 属性添加
     * @param index
     */
    addSpecAttr(index) {
        let specList = this.state.specList;
        let specValue = specList[index].value;
        let tagName = this.field.getValue(`tagName[${index}]`);
        if (!tagName.trim()) return;
        tagName = tagName.trim();
        let tagNames = tagName.split(/\s+/);
        //数组去重
        let newArr = specValue.concat(tagNames);
        newArr = Array.from(new Set(newArr));
        specList[index].value = newArr;
        this.field.setValue(`tagName[${index}]`, '');
        this.handleSpecChange(specList,'add');
    }

    /**
     * 属性删除
     * @param index
     * @param num
     * @returns {boolean}
     */
    delAttr(index, num) {
        let specList = this.state.specList;
        specList[index].value.splice(num, 1);
        this.handleSpecChange(specList, 'del');
        return false;
    }

    /**
     * 规格删除
     * @param index
     */
    delSpec(index) {
        let specList = this.state.specList;
        specList.splice(index, 1);
        this.handleSpecChange(specList, 'del');
    }

    //添加规格
    addSpec() {
        const specList = this.state.specList;
        if (specList.length < 5) {
            specList.push({
                name: '',
                value: []
            })
        } else {
            Message.error('最多添加5个规格')
        }
        this.handleSpecChange(specList);
    }

    /**
     * 监听标签的变化
     * @param specList
     * @param option
     */
    handleSpecChange(specList,option) {
        const stockCopy = JSON.parse(JSON.stringify(this.state.specAttrList));
        if (option === 'del') this.state.specAttrList = [];
        for (let i = 0; i < this.countSum(0); i++) {
            this.changeStock(option, i, stockCopy)
        }
        this.setState({specList: specList});
        console.log(this.state.specAttrList)
    }

    /**
     * 属性改变时处理
     * @param option
     * @param index
     * @param stockCopy
     */
    changeStock(option,index,stockCopy){
        option = option || '';
        let specAttrList = this.state.specAttrList;
        let attrLists = {
            id: index,
            attr_list: this.getChildGoodsAttr(index),
            //  spec_no: this.defaultProductNo + index,
            price: 0,
            bar_code: '',
        };
        const specs = attrLists.attr_list;
        if (option === 'add') {
            // 如果此id不存在，新增属性
            let attrList = specAttrList.map((item)=>item.attr_list);
            if (attrList.findIndex((item) => this.objEquals(specs, item)) === -1) {
                specAttrList.push(attrLists);
                this.setState({specAttrList:specAttrList});
            }
        } else if (option === 'del') {
            let originData = '';
            stockCopy.forEach(item => {
                if (this.objEquals(specs, item.attr_list)) {
                    originData = item;
                    return false;
                }
            });
            specAttrList.push(originData || attrLists);
            this.setState({specAttrList:specAttrList});
        }
    }

    /**
     * 获取属性规格
     * @param index
     */
    getChildGoodsAttr (index) {
        let obj = {};
        this.state.specList.forEach((item, specIndex) => {
            obj[item.name] = this.getSpecAttr(specIndex, index)
        });
        return obj;
    }

    /**
     * 为Object添加一个原型方法，判断两个对象是否相等
     * @param object1
     * @param object2
     * @returns {boolean}
     */
    objEquals (object1, object2) {
        for (let propName in object1) {
            if (object1.hasOwnProperty(propName) !== object2.hasOwnProperty(propName)) {
                return false
            } else if (typeof object1[propName] !== typeof object2[propName]) {
                return false
            }
        }
        for (let propName in object2) {
            if (object1.hasOwnProperty(propName) !== object2.hasOwnProperty(propName)) {
                return false
            } else if (typeof object1[propName] !== typeof object2[propName]) {
                return false
            }
            if (!object1.hasOwnProperty(propName)) {
                continue
            }
            if (object1[propName] instanceof Array && object2[propName] instanceof Array) {
                if (this.objEquals(!object1[propName], object2[propName])) {
                    return false
                }
            } else if (object1[propName] instanceof Object && object2[propName] instanceof Object) {
                if (this.objEquals(!object1[propName], object2[propName])) {
                    return false
                }
            } else if (object1[propName] !== object2[propName]) {
                return false
            }
        }
        return true
    }
}

export default Sku;
